package com.eastmoney.emis.edda.task.eddi;

import com.eastmoney.emis.edda.domain.entity.EddiInstruction;
import com.eastmoney.emis.edda.domain.repository.HsbcEddiRepository;
import com.eastmoney.emis.edda.domain.service.EddaServeTimeService;
import com.eastmoney.emis.edda.domain.valueobject.EddiStatus;
import com.eastmoney.emis.edda.domain.valueobject.ServiceType;
import com.eastmoney.emis.edda.task.TaskManagement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @description: Description
 * @projectName: EDDA-HSBC
 * @package: com.eastmoney.emis.edda.task
 * @author: 汪程程
 * @date: 2022/10/10 1:44 PM
 * @version: 1.0
 */
@Component
@Async("eddaTaskExecutor")
public class EddiTaskProducer {

    private static Logger log = LoggerFactory.getLogger(EddiTaskProducer.class);

    @Autowired
    private TaskManagement taskManagement;
    @Autowired
    private HsbcEddiRepository hsbcEddiRepository;
    @Autowired
    private EddaServeTimeService eddaServeTimeService;
    private static final LocalTime ADJUSTER = LocalTime.of(8, 30, 0);

    @Scheduled(cron = "${emis.edda.task.eddi-cron:*/15 * * * * ?}")
    public void loadEddiApplyFromDB() {
        // 周一check 每周一上午的入金，统一从8点30分开始处理。EMIS-1901
        LocalDateTime now = LocalDateTime.now();
        if (now.getDayOfWeek() == DayOfWeek.MONDAY && now.isBefore(now.with(ADJUSTER))) {
            return;
        }

        if (!eddaServeTimeService.serving(ServiceType.EDDI)) {
            return;
        }
        Instant instant = LocalDateTime.now()
                .minus(15, ChronoUnit.DAYS)
                .atZone(ZoneId.systemDefault())
                .toInstant();
        // 需求: 开户时授权并入金, 优先处理金额不小于10,000的那一笔
        // 设计: 由于业务流程，开户时只能一笔一笔提交入金申请，需求可以简化为 优先处理金额大的那一笔
        // 实现: order by OCCURBALANCE desc
        List<EddiInstruction> eddiInstructions = hsbcEddiRepository.findAllUncompletedByEITime(Date.from(instant));
        for (EddiInstruction eddiInstruction : eddiInstructions) {
            taskManagement.addTask(new EddiTask(eddiInstruction));
        }

    }

}
